package com.yonyou.gmmc.service.violationInquiry.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.marketing.common.FrameHttpUtil;
import org.marketing.common.constants.ExceptionMessage;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.dto.customerInfo.MemberDto;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.CopyOfStringUtil;
import org.marketing.common.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonyou.gmmc.common.service.BaseService;
import com.yonyou.gmmc.service.violationInquiry.constant.ViolationInquiryConstant;
import com.yonyou.gmmc.service.violationInquiry.dao.TmRegCitiesMapper;
import com.yonyou.gmmc.service.violationInquiry.dao.TmRegProMapper;
import com.yonyou.gmmc.service.violationInquiry.dao.TmRegulationsDetailMapper;
import com.yonyou.gmmc.service.violationInquiry.dao.TmRegulationsDetailTempMapper;
import com.yonyou.gmmc.service.violationInquiry.dao.TmRegulationsMapper;
import com.yonyou.gmmc.service.violationInquiry.dao.TmRegulationsThridMapper;
import com.yonyou.gmmc.service.violationInquiry.model.TmRegCities;
import com.yonyou.gmmc.service.violationInquiry.model.TmRegPro;
import com.yonyou.gmmc.service.violationInquiry.model.TmRegulations;
import com.yonyou.gmmc.service.violationInquiry.model.TmRegulationsDetail;
import com.yonyou.gmmc.service.violationInquiry.model.TmRegulationsDetailTemp;
import com.yonyou.gmmc.service.violationInquiry.model.TmRegulationsThrid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
@Transactional
public class ViolationInquiryService extends BaseService {

	private static Logger logger = LoggerFactory.getLogger(ViolationInquiryService.class);

	@Autowired
	private TmRegulationsMapper tmRegulationsMapper;
	@Autowired
	private TmRegulationsDetailMapper tmRegulationsDetailMapper;
	@Autowired
	private TmRegProMapper tmRegProMapper;
	@Autowired
	private TmRegCitiesMapper tmRegCitiesMapper;
	@Autowired
	private TmRegulationsThridMapper tmRegulationsThridMapper;
	@Autowired
	private TmRegulationsDetailTempMapper tmRegulationsDetailTempMapper;
	@Autowired
	private SaveThridService saveThridService;

	@Value("${CYX_URL}")
	private String CYX_URL;
	@Value("${CYX_NAME}")
	private String CYX_NAME;
	@Value("${CYX_PWD}")
	private String CYX_PWD;
	@Value("${CYX_CITY_URL}")
	private String CYX_CITY_URL;
	@Value("${violationInquiryFlag}")
	private Integer violationInquiryFlag;
	@Value("${VIOLATIONTIME}")
	private Integer violationTime;

	public List<TmRegulationsDetail> findRegs(Map<String, String> map) throws UnsupportedEncodingException {
//		logger.info("ViolationInquiryService.findRegs==>registNo:" + map.get("registNo") + "   vin:" + map.get("vin")
//				+ "   engine:" + map.get("engine"));
		// 处理车牌号，广丰车牌中有“-”和“.”或者其他分隔字符则去掉
		String regist = manageRegistNo(map.get("registNo"));
		// 根据请求规则，组合请求的URL
		String content = requestContent(map.get("vin"), map.get("engine"), regist);
		content = "userid=" + CYX_NAME + "&userpwd=" + URLEncoder.encode(CYX_PWD, "UTF-8") + "&" + content;
		String returnJson = FrameHttpUtil.sendPost(CYX_URL, content);
		logger.info("返回的JSON为：" + returnJson);
		// 保存访问http请求记录
		if (CheckUtil.NullOrEmpty(returnJson)) {
			logger.info("违章查询返回为空");
			throw new ServiceBizException(ExceptionMessage.APP_REGULATIONS_SYSTEM_ERROR);
		}
		saveThridService.saveRegulationsHttp(map, returnJson);
		// 解析请求返回的信息。
		List<TmRegulationsDetail> list = parse2Reg(returnJson);

		return list;
	}

	public List<TmRegCities> checkCarReg(Map<String, Object> map) {
//		logger.info("ViolationInquiryService.checkCarReg==>registNo:" + map.get("registNo"));
		if (map.get("cityCode") == null) {
			throw new ServiceBizException("获取参数为空！");
		}
		String cityCode = map.get("cityCode").toString();
		Example ex = new Example(TmRegCities.class);
		Criteria criteria = ex.createCriteria();
		criteria.andEqualTo("cityId", cityCode);

		List<TmRegCities> list = tmRegCitiesMapper.selectByExample(ex);
		if (CheckUtil.NullOrEmpty(list)) {
			throw new ServiceBizException("该地区暂不支持违章查询!");
		}
		return list;
	}

	// 处理请求内容
	private String requestContent(String vin, String engine, String registNo) throws UnsupportedEncodingException {
		String carcode = vin;
		String cardrivenumber = engine;
		String reg_Sp = registNo.substring(0, 1);
		String reg_prefix = "";
		if (reg_Sp.equals("京") || reg_Sp.equals("沪") || reg_Sp.equals("津") || reg_Sp.equals("渝")) {
			reg_prefix = reg_Sp;
		} else {
			reg_prefix = registNo.substring(0, 2);
		}
		TmRegCities city = loadCity(reg_prefix);
		if (!CheckUtil.NullOrEmpty(city)) {
			if (city.getCarCodeLen() == 0) {
				carcode = "";
			} else if (city.getCarCodeLen() == 99) {
			} else {
				if (vin.length() >= city.getCarCodeLen()) {
					carcode = vin.substring(vin.length() - city.getCarCodeLen(), vin.length());
				}
			}

			if (city.getCarEngineLen() == 0) {
				cardrivenumber = "";
			} else if (city.getCarEngineLen() == 99) {
			} else {
				if (engine.length() >= city.getCarEngineLen()) {
					cardrivenumber = engine.substring(engine.length() - city.getCarEngineLen(), engine.length());
				}
			}
		}

		String content = "carnumber=" + URLEncoder.encode(registNo, "UTF-8") + "&carcode=" + carcode
				+ "&cardrivenumber=" + cardrivenumber;
		return content;
	}

	// 处理车牌
	private String manageRegistNo(String registNo) {
		String regtNo = registNo;
		if (!CheckUtil.NullOrEmpty(registNo) && registNo.length() == 8) {
			if (registNo.charAt(2) == '-') {
				regtNo = registNo.replaceFirst("-", "");
			}
			if (registNo.charAt(2) == '.') {
				regtNo = registNo.replaceFirst(".", "");
			}
		}
		return regtNo;
	}

	// 解析返回的Json信息
	private static List<TmRegulationsDetail> parse2Reg(String returnJson) {
		List<TmRegulationsDetail> list = new ArrayList<>();
		
		JSONObject node = JSONObject.fromObject(returnJson);
		String ErrorCode = node.getString("ErrorCode");
		String ErrMessage = node.getString("ErrMessage");
		Boolean HasData = node.getBoolean("HasData");
		if (Integer.parseInt(ErrorCode) != 0) {
			logger.error("违章查询出现问题:" + ErrMessage);
			if (Integer.parseInt(ErrorCode) == -3) {
				// 本系统暂不提供该城市违章查询请求
				throw new ServiceBizException(ExceptionMessage.APP_REGULATIONS_SUPPORT_ERROR);
			} else if (Integer.parseInt(ErrorCode) == -42) {
				// 数据源暂不可用
				throw new ServiceBizException(ExceptionMessage.APP_REGULATIONS_DATASOURSE_ERROR);
			} else if (Integer.parseInt(ErrorCode) == -6) {
				// 您输入信息有误
				throw new ServiceBizException(ExceptionMessage.APP_REGULATIONS_INPUTINFO_ERROR);
			} else if (Integer.parseInt(ErrorCode) == -61) {
				// 输入车牌号有误
				throw new ServiceBizException(ExceptionMessage.APP_REGULATIONS_REGISTNO_ERROR);
			} else if (Integer.parseInt(ErrorCode) == -62) {
				// 输入车架号有误
				throw new ServiceBizException(ExceptionMessage.APP_REGULATIONS_VIN_ERROR);
			} else if (Integer.parseInt(ErrorCode) == -63) {
				// 输入发动机号有误
				throw new ServiceBizException(ExceptionMessage.APP_REGULATIONS_ENGINE_ERROR);
			} else if (Integer.parseInt(ErrorCode) == -66) {
				// 不支持的车辆类型
				throw new ServiceBizException(ExceptionMessage.APP_REGULATIONS_VINTYPE_ERROR);
			} else if (Integer.parseInt(ErrorCode) == -67) {
				// 该省份（城市）不支持异地车牌
				throw new ServiceBizException(ExceptionMessage.APP_REGULATIONS_OUTCITYREGISTNO_ERROR);
			} else {
				throw new ServiceBizException(ExceptionMessage.APP_REGULATIONS_SYSTEM_ERROR);
			}
		}
		if (HasData) {
			JSONArray violationRecords = JSONArray.fromObject(node.get("Records"));
			for (Object o : violationRecords) {
				TmRegulationsDetail po = new TmRegulationsDetail();
				JSONObject jsonNode = JSONObject.fromObject(o);
				String time = jsonNode.getString("Time");
				String location = jsonNode.getString("Location");
				String reason = jsonNode.getString("Reason");
				String count = jsonNode.getString("count");
				String status = jsonNode.getString("status");
				String department = jsonNode.getString("department");
				String degree = jsonNode.getString("Degree");
				String code = jsonNode.getString("Code");
				String archive = jsonNode.getString("Archive");
				String telephone = jsonNode.getString("Telephone");
				String excuteLocation = jsonNode.getString("Excutelocation");
				String excuteDepartment = jsonNode.getString("Excutedepartment");
				String category = jsonNode.getString("Category");
				String latefine = jsonNode.getString("Latefine");
				String punishmentAccording = jsonNode.getString("Punishmentaccording");
				String illegalentry = jsonNode.getString("Illegalentry");

				String locationId = jsonNode.getString("Locationid");
				String locationName = jsonNode.getString("LocationName");
				String datasourceId = jsonNode.getString("DataSourceID");
				String recordType = jsonNode.getString("RecordType");

				String poundage = jsonNode.getString("Poundage");
				String canProcess = jsonNode.getString("CanProcess");
				String secondaryUniqueCode = jsonNode.getString("SecondaryUniqueCode");
				String canprocessMsg = jsonNode.getString("CanprocessMsg");
				String uniqueCode = jsonNode.getString("UniqueCode");

				String degreePoundage = jsonNode.getString("DegreePoundage");
				String other = jsonNode.getString("Other");
				if (canProcess.equals("1"))
					logger.debug("违章ID:" + secondaryUniqueCode + ", 此违章可代办，在下单接口中将此ID传入");
				logger.debug("======================接口返回的违章信================================");
				logger.debug("返回Time:" + time);
				logger.debug("返回Location:" + location);
				logger.debug("返回Reason:" + reason);
				logger.debug("返回count:" + count);
				logger.debug("返回status:" + status);
				logger.debug("返回department:" + department);
				logger.debug("返回Degree:" + degree);
				logger.debug("返回Code:" + code);

				logger.debug("返回Archive:" + archive);
				logger.debug("返回telephone:" + telephone);
				logger.debug("返回Excutedepartment:" + excuteDepartment);
				logger.debug("返回Locationid:" + locationId);
				logger.debug("返回LocationName:" + locationName);
				logger.debug("返回DataSourceID" + datasourceId);
				logger.debug("返回Poundage:" + poundage);
				logger.debug("返回CanprocessMsg:" + canprocessMsg);
				logger.debug("返回SecondaryUniqueCode:" + secondaryUniqueCode);
				logger.debug("======================================================");

				po.setTime(DateUtil.dateFormat(time, "yyyy-MM-dd HH:mm:ss"));
				// 把时间戳 转成 2017-04-02 星期二 20:07:00
				po.setExcuteTime(time.substring(0, 11)
						+ DateUtil.getWeek(DateUtil.dateFormat(time, "yyyy-MM-dd HH:mm:ss")) + time.substring(10));
				po.setLocation(location);
				po.setReason(reason);
				if (!CheckUtil.NullOrEmpty(count)) {
					po.setCount(Integer.parseInt(count));
				} else {
					po.setCount(0);
				}
				po.setStatus(status);
				if (!CheckUtil.NullOrEmpty(department)) {
					po.setDepartment(department);
				}
				if (!CheckUtil.NullOrEmpty(degree)) {
					po.setDegree(Integer.parseInt(degree));
				} else {
					po.setDegree(0);
				}
				po.setCode(code);
				po.setArchive(archive);
				if (!CheckUtil.NullOrEmpty(telephone)) {
					po.setTelephone(telephone);
				}
				if (!CheckUtil.NullOrEmpty(excuteLocation)) {
					po.setExcuteLocation(excuteLocation);
				}
				if (!CheckUtil.NullOrEmpty(excuteDepartment)) {
					po.setExcuteDepartment(excuteDepartment);
				}
				po.setCategory(category);
				if (!CheckUtil.NullOrEmpty(latefine)) {
					po.setLateFine(Integer.parseInt(latefine));
				} else {
					po.setLateFine(0);
				}
				if (!CheckUtil.NullOrEmpty(punishmentAccording)) {
					po.setPunishmentAccording(punishmentAccording);
				}
				if (!CheckUtil.NullOrEmpty(illegalentry)) {
					po.setIllegalentry(illegalentry);
				}
				po.setLocationId(locationId);
				po.setLocationName(locationName);
				po.setDatasourceId(datasourceId);
				po.setRecordType(recordType);
				if (!CheckUtil.NullOrEmpty(poundage)) {
					po.setPoundage(Integer.parseInt(poundage));
				} else {
					po.setPoundage(0);
				}
				po.setCanProcess(canProcess);
				if (!CheckUtil.NullOrEmpty(canprocessMsg)) {
					po.setCanprocessMsg(canprocessMsg);
				}
				if (!CheckUtil.NullOrEmpty(secondaryUniqueCode)) {
					po.setSecondaryUniqueCode(Long.valueOf(secondaryUniqueCode));
				} else {
					logger.error("返回数据的唯一标识为空");
					continue;
				}
				po.setUniqueCode(uniqueCode);
				if (!CheckUtil.NullOrEmpty(degreePoundage)) {
					po.setDegreePoundage(Integer.parseInt(degreePoundage));
				} else {
					po.setDegreePoundage(0);
				}
				po.setOther(other);

				list.add(po);
			}
		}

		return list;
	}

	public Map<String, Object> updateCarReg(Map<String, String> map) throws Exception {
		Integer userId = Integer.valueOf(map.get("userId"));
		Map<String, Object> result = new HashMap<>();
		/*Integer queryNum = tmRegulationsMapper.queryViolationInquiryNum(userId, DateUtil.formateDate(new Date(), "yyyy-MM-dd"));
		if(queryNum>=violationInquiryFlag){
			result.put(ResultMsgConstants.RESULT_MESSAGE, "违章查询每天只能查询"+violationInquiryFlag+"次");
			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
			return result;
		}*/
		// 扣分总数
		Integer sumNum = 0;
		// 罚款总数
		Integer sumMoney = 0;
		
		String vin = map.get("vin");
		String registNo = map.get("registNo");
		String engine = map.get("engine");
		// 保存查询历史
		saveThridService.saveThrid(map);
		List<TmRegulationsDetail> list = null;
		Long bDate = System.currentTimeMillis() - violationTime;
		Map<String, Object> dateMap = tmRegulationsMapper.queryViolationTime(registNo, vin, engine, new Date(bDate));
		Integer dateNum = dateMap==null?0:Integer.valueOf(dateMap.get("bdate").toString());
		Integer regulations_id = dateMap==null?0:Integer.valueOf(dateMap.get("regulations_id").toString());
		if(dateNum>0){
			TmRegulationsDetail RegDetail = new TmRegulationsDetail();
			RegDetail.setRegulationsId(regulations_id);
			RegDetail.setStatus("0");
			list = tmRegulationsDetailMapper.select(RegDetail);
			for (TmRegulationsDetail po : list) {
				sumNum += po.getDegree();
				sumMoney += po.getCount();
			}
		}else{
			Integer reg_id = tmRegulationsMapper.queryPK();
			map.put("reg_id", reg_id.toString());
			list = findRegs(map);
			List<TmRegulationsDetail> strUQ = new ArrayList<>();
			if (!CheckUtil.NullOrEmpty(list) && !list.isEmpty()) {
				// 处理违章主表信息
				TmRegulations tr = new TmRegulations();
				
				if (vin != null && !"".equals(vin)) {
					tr.setVin(vin);
				}
				if (engine != null && !"".equals(engine)) {
					tr.setEngine(engine);
				}
				tr.setRegulationsId(reg_id);
				tr.setRegistNo(manageRegistNo(registNo));
				tr.setCreateBy(ViolationInquiryConstant.OPT_USER);
				tr.setCreateDate(DateUtil.currentDateTime());
				tr.setQueryUser(userId);
				tmRegulationsMapper.insertSelective(tr);

				/**
				 * 唯一标示 uniqueCode 改为 time 和 location 判断
				 */
				// 处理违章从表信息
				for (TmRegulationsDetail po : list) {
					// 判断是否存在，不存则新增，存在则更新时间
					TmRegulationsDetail regDetail = new TmRegulationsDetail();
					TmRegulationsDetail regDetailUpdate = new TmRegulationsDetail();

					regDetail.setTime(po.getTime());
					regDetail.setLocation(po.getLocation());

					List<TmRegulationsDetail> detailList = tmRegulationsDetailMapper.select(regDetail);
					if (!CheckUtil.NullOrEmpty(detailList) && !detailList.isEmpty()) {
						regDetailUpdate.setUpdateBy(ViolationInquiryConstant.OPT_USER);
						regDetailUpdate.setUpdateDate(DateUtil.currentDateTime());
						regDetailUpdate.setUniqueCode(po.getUniqueCode());
						regDetailUpdate.setRegulationsId(reg_id);
						Example ex = new Example(TmRegulationsDetail.class);
						Criteria criteria = ex.createCriteria();
						criteria.andEqualTo("time", detailList.get(0).getTime());
						criteria.andEqualTo("location", detailList.get(0).getLocation());
						tmRegulationsDetailMapper.updateByExampleSelective(regDetailUpdate, ex);
					} else {
						po.setRegulationsId(reg_id);
						po.setCreateBy(ViolationInquiryConstant.OPT_USER);
						po.setCreateDate(DateUtil.currentDateTime());
						tmRegulationsDetailMapper.insertSelective(po);
					}
					// 违章详情复表，以后做报表时使用
					TmRegulationsDetailTemp tempPo = new TmRegulationsDetailTemp();
					CopyOfStringUtil.Copy(po, tempPo);
					tempPo.setRegulationsId(reg_id);
					tmRegulationsDetailTempMapper.insertSelective(tempPo);
					sumNum += po.getDegree();
					sumMoney += po.getCount();
					TmRegulationsDetail trd = new TmRegulationsDetail();
					trd.setTime(po.getTime());
					trd.setLocation(po.getLocation());
					strUQ.add(trd);
				}
				List<Map<String, Object>> _list = tmRegulationsDetailMapper.selectDetail(reg_id);
				if (!CheckUtil.NullOrEmpty(_list) && !_list.isEmpty()) {
					for (int i = 0; i < _list.size(); i++) {
						boolean flag = false;
						String time = String.valueOf(_list.get(i).get("time"));
						String location = String.valueOf(_list.get(i).get("location"));
						for (int j = 0; j < strUQ.size(); j++) {
							String time2 = DateUtil.formateDate(strUQ.get(j).getTime(), "yyyy-MM-dd HH:mm:ss");
							if (time.equals(time2) && location.equals(strUQ.get(j).getLocation())) {
								flag = true;
								break;
							}
						}
						if (!flag) {
							Map<String, Object> param = new HashMap<>();
							param.put("reg_id", reg_id);
							param.put("time", time);
							param.put("location", location);
							tmRegulationsDetailMapper.updateDetail(param);
						}
					}
				}
			} else {
				// 处理查询成功，并且没有违章的情况
				TmRegulations tr = new TmRegulations();
				tr.setRegistNo(manageRegistNo(registNo));
				if (vin != null && !"".equals(vin)) {
					tr.setVin(vin);
				}
				if (engine != null && !"".equals(engine)) {
					tr.setEngine(engine);
				}
				// 判断是否存在违章信息，不存在则新增，存在则修改更新时间
				List<TmRegulations> regulList = tmRegulationsMapper.select(tr);
				if (!CheckUtil.NullOrEmpty(regulList) && !regulList.isEmpty()) {
					TmRegulations regulPO = regulList.get(0);
					if (!CheckUtil.NullOrEmpty(regulPO) && !"".equals(regulPO.getRegulationsId())) {
						TmRegulationsDetail record = new TmRegulationsDetail();
						record.setRegulationsId(regulPO.getRegulationsId());
						record.setStatus("1");
						tmRegulationsDetailMapper.updateByPrimaryKeySelective(record);
					}
				}
			}
		}
		

		Map<String, Object> carMap = tmRegulationsMapper.queryCar(registNo);
		if (carMap != null && !carMap.isEmpty()) {
			result.put("seriesName", carMap.get("seriesName"));
			result.put("carName", carMap.get("carName"));
			result.put("picUrl", carMap.get("picUrl"));
		} else {
			result.put("seriesName", null);
			result.put("carName", null);
			result.put("picUrl", null);
		}
		result.put("registNo", registNo);
		result.put("sumNum", sumNum);
		result.put("sumMoney", sumMoney);
		// 违规总数
		result.put("illeagalNum", list.size());
		result.put("list", list);
		result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_SUCCESS);
		result.put(ResultMsgConstants.RESULT_MESSAGE, "");
		return result;
	}

	public TmRegCities loadCity(String c) {
		TmRegCities r = new TmRegCities();
		r.setCarNumberPrefix(c);
		TmRegCities list = tmRegCitiesMapper.selectOne(r);
		return list;
	}

	public void parse2City() {
		String returnJson = FrameHttpUtil.sendPost(CYX_CITY_URL, "");
		logger.info("查询违章城市返回的JSON为：" + returnJson);
		if (!CheckUtil.NullOrEmpty(returnJson)) {
			JSONArray jaPro = JSONArray.fromObject(returnJson);
			for (Object objPro : jaPro) {
				Short provinceID = 0;
				try {
					JSONObject js = JSONObject.fromObject(objPro);
					TmRegPro tPro = new TmRegPro();
					provinceID = Short.valueOf(js.getString("ProvinceID"));
					JSONArray ja = JSONArray.fromObject(js.get("Cities"));
					tPro.setProvinceId(Short.valueOf(provinceID));
					tPro.setProvinceName(js.getString("ProvinceName"));
					tPro.setProvincePrefix(js.getString("ProvincePrefix"));
					TmRegPro pro = new TmRegPro();
					pro.setProvinceId(provinceID);
					int i = tmRegProMapper.selectCount(pro);
					if (i > 0) {
						tPro.setUpdateBy(ViolationInquiryConstant.OPT_USER);
						tPro.setUpdateDate(DateUtil.currentDateTime());
						tmRegProMapper.updateByPrimaryKeySelective(tPro);
					} else {
						tPro.setCreateBy(ViolationInquiryConstant.OPT_USER);
						tPro.setCreateDate(DateUtil.currentDateTime());
						tmRegProMapper.insertSelective(tPro);
					}
					if (!CheckUtil.NullOrEmpty(ja) && !ja.isEmpty()) {
						for (Object obj : ja) {
							Integer cityID = 0;
							try {
								TmRegCities tCity = new TmRegCities();
								JSONObject node = JSONObject.fromObject(obj);
								tCity.setProvinceId(provinceID);
								cityID = node.getInt("CityID");
								tCity.setCityId(cityID);
								tCity.setCityName(node.getString("CityName"));
								tCity.setName(node.getString("Name"));
								tCity.setCarNumberPrefix(node.getString("CarNumberPrefix"));
								tCity.setCarCodeLen(Short.valueOf(node.getString("CarCodeLen")));
								tCity.setCarEngineLen(Short.valueOf(node.getString("CarEngineLen")));
								TmRegCities city = new TmRegCities();
								city.setCityId(cityID);
								int k = tmRegCitiesMapper.selectCount(city);
								if (k > 0) {
									tCity.setUpdateBy(ViolationInquiryConstant.OPT_USER);
									tCity.setUpdateDate(DateUtil.currentDateTime());
									tmRegCitiesMapper.updateByPrimaryKeySelective(tCity);
								} else {
									tCity.setCreateBy(ViolationInquiryConstant.OPT_USER);
									tCity.setCreateDate(DateUtil.currentDateTime());
									tmRegCitiesMapper.insertSelective(tCity);
								}
							} catch (Exception ex) {
								logger.info("保存违章市" + cityID + "失败：" + ex.getMessage());
								throw new ServiceBizException(ex.getMessage(), ex);
							}
						}
					}
				} catch (Exception ex) {
					logger.info("保存违章省" + provinceID + "失败：" + ex.getMessage());
					throw new ServiceBizException(ex.getMessage(), ex);
				}
			}
		}

	}

	public Map<String, Object> checkCar(Map<String, Object> map) {
		Map<String, Object> result = new HashMap<>();
		Integer userId = Integer.valueOf(map.get("userId").toString());
		logger.info("ViolationInquiryService.checkCar==>userId:" + map.get("userId"));
		MemberDto memberDto = tmRegulationsMapper.queryMember(userId);
		// 判断是否为会员
		if (memberDto == null) {
			logger.info(">>>>>粉丝不能使用！");
			result.put("typeCode", "0");
			result.put("typeName", "粉丝");
			return result;
		}
		// 判断是否为会员
		if (memberDto != null && memberDto.getVin() == null) {
			logger.info(">>>>>该用户为会员！");
			result.put("typeCode", "1");
			result.put("typeName", "会员");
			return result;
		}
		String carnumber = "";
		String vin = "";
		String engine = "";
		if (memberDto != null) {
			carnumber = memberDto.getLicenseNo();
			vin = memberDto.getVin();
			engine = memberDto.getEngine();
		}
		String reg_prefix = "";
		if (carnumber != null && !"".equals(carnumber)) {
			String reg_Sp = carnumber.substring(0, 1);
			if (reg_Sp.equals("京") || reg_Sp.equals("沪") || reg_Sp.equals("津") || reg_Sp.equals("渝")) {
				reg_prefix = reg_Sp;
			} else {
				reg_prefix = carnumber.substring(0, 2);
			}
			TmRegCities city = loadCity(reg_prefix);
			if (!CheckUtil.NullOrEmpty(city)) {
				if (city.getCarCodeLen() == 0) {
					vin = "";
				} else if (city.getCarCodeLen() == 99) {
				} else {
					if (vin.length() >= city.getCarCodeLen()) {
						vin = vin.substring(vin.length() - city.getCarCodeLen(), vin.length());
					}
				}

				if (city.getCarEngineLen() == 0) {
					engine = "";
				} else if (city.getCarEngineLen() == 99) {
				} else {
					if (engine.length() >= city.getCarEngineLen()) {
						engine = engine.substring(engine.length() - city.getCarEngineLen(), engine.length());
					}
				}
			}
		}
		String licenseNo = carnumber.replaceAll(" ", "");
		result.put("typeCode", "2");
		result.put("typeName", "车主");
		result.put("vin", vin);
		result.put("licenseNo", licenseNo);
		result.put("engine", engine);

		return result;
	}

	public List<TmRegulationsThrid> findHistory(Map<String, Object> map) {
		logger.info("ViolationInquiryService.findHistory==>userId:" + map.get("userId"));

		Integer userId = Integer.valueOf(map.get("userId").toString());
		return tmRegulationsThridMapper.findHistory(userId);
	}

	public Integer deleteHistory(Map<String, Object> map) {
		logger.info("ViolationInquiryService.findHistory==>openId:" + map.get("userId"));
		Integer userId = Integer.valueOf(map.get("userId").toString());
		Example example = new Example(TmRegulationsThrid.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userId", userId);
		TmRegulationsThrid po = new TmRegulationsThrid();
		po.setResCode((short) 0);
		po.setUpdateDate(new Date());
		po.setUpdateBy(ViolationInquiryConstant.OPT_USER);
		Integer i = tmRegulationsThridMapper.updateByExampleSelective(po, example);
		return i;
	}

	public List<Map<String,Object>> findProvince() {
		logger.info("ViolationInquiryService.findProvince==>");
		List<Map<String,Object>> result = new ArrayList<>();
		List<TmRegPro> proList = tmRegProMapper.selectAll();
		if (proList.size()>0) {
			for (TmRegPro regPro : proList) {
				Map<String,Object> firstMap = new HashMap<>();
                List<Map<String,Object>> deList = new ArrayList<>();
                TmRegCities rc = new TmRegCities();
                rc.setProvinceId(regPro.getProvinceId());
                List<TmRegCities> cityList = tmRegCitiesMapper.select(rc);
                if(cityList.size()>0){
                    for(TmRegCities child : cityList){
                    	Map<String,Object> deMap = new HashMap<>();
                        deMap.put("name", child.getName());
                        deMap.put("id", child.getCityId());
                        deMap.put("shortName", regPro.getProvincePrefix());
                        deList.add(deMap);
                    }
                }
                firstMap.put("shortName", regPro.getProvincePrefix());
                firstMap.put("name", regPro.getProvinceName());
                firstMap.put("id", regPro.getProvinceId());
                firstMap.put("child", deList);
                result.add(firstMap);
			}
		}else{
			throw new ServiceBizException("违章查询支持城市列表为空");
		}

		return result;
	}

}
